<template>
  <el-container>
    <el-main>
      <el-form :model="form.model" :rules="form.rules" ref="formRef" label-width="100px">
        <el-form-item label="模板名称" prop="name">
          <el-input v-model="form.model.name" placeholder="请输入模板名称"></el-input>
        </el-form-item>
        <el-form-item label="备注">
          <el-input type="textarea" v-model="form.model.memo" placeholder="请输入备注"></el-input>
        </el-form-item>
        <el-form-item v-if="modal?.params.templateType == 'template'" label="发布平台">
          <el-checkbox-group v-model="form.model.platform">
            <el-checkbox label="WechatOfficialAccount">微信公众号</el-checkbox>
            <el-checkbox label="WechatMiniProgram">微信小程序</el-checkbox>
            <el-checkbox label="H5">H5</el-checkbox>
            <el-checkbox label="App">APP</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
    </el-main>
    <el-footer class="sa-footer--submit">
      <el-button
        v-if="modal.params.type == 'add'"
        v-auth="'shop.admin.decorate.template.add'"
        type="primary"
        @click="confirm"
        >保存</el-button
      >
      <el-button
        v-if="modal.params.type == 'edit'"
        v-auth="'shop.admin.decorate.template.edit'"
        type="primary"
        @click="confirm"
        >更新</el-button
      >
    </el-footer>
  </el-container>
</template>
<script setup>
  import { onMounted, reactive, ref, unref } from 'vue';
  import { api } from '../decorate.service';
  import { cloneDeep } from 'lodash';

  const emit = defineEmits(['modalCallBack']);
  const props = defineProps({
    modal: {
      type: Object,
    },
  });

  // 添加 编辑 form
  let formRef = ref(null);
  const form = reactive({
    model: {
      type: props.modal.params.templateType,
      name: '',
      memo: '',
      platform: [],
    },
    rules: {},
  });
  const loading = ref(false);
  // 获取详情
  async function getDetail(id) {
    loading.value = true;
    const { error, data } = await api.template.detail(id);
    error === 0 && (form.model = data);
    loading.value = false;
  }

  // 表单关闭时提交
  function confirm() {
    unref(formRef).validate(async (valid) => {
      if (!valid) return;
      let submitForm = cloneDeep(form.model);
      const { error } =
        props.modal.params.type == 'add'
          ? await api.template.add(submitForm)
          : await api.template.edit(props.modal.params.id, submitForm);
      if (error == 0) {
        emit('modalCallBack', { event: 'confirm' });
      }
    });
  }

  onMounted(() => {
    if (props.modal.params.type == 'edit') {
      getDetail(props.modal.params.id);
    }
  });
</script>
